const TFT_MOSI = 19;
const TFT_SCLK = 18;
const TFT_CS = 5; 
const TFT_DC = 16;
const TFT_BL = 4;
const TFT_WIDTH = 135;
const TFT_HEIGHT = 240;

gpio.pinMode(TFT_CS, gpio.GPIO_MODE_OUTPUT)
gpio.pinMode(TFT_BL, gpio.GPIO_MODE_OUTPUT)
gpio.pinMode(TFT_DC, gpio.GPIO_MODE_OUTPUT)
gpio.write(TFT_BL, 1)
spi.init(0, 1000000, -1, TFT_MOSI, TFT_SCLK)

function tftWrite8(u8, isData) {
    gpio.write(TFT_DC, isData? 1 : 0);
    gpio.write(TFT_CS, 0)
    spi.writeBits(0, u8, 8)
    gpio.write(TFT_CS, 1)
}

function tftWrite32(u32, isData) {
    gpio.write(TFT_DC, isData? 1 : 0);
    gpio.write(TFT_CS, 0)
    spi.writeBits(0, u32, 32)
    gpio.write(TFT_CS, 1)
}

function tftWriteBuf(buf, len, isData) {
    gpio.write(TFT_DC, isData? 1 : 0);
    gpio.write(TFT_CS, 0)
    spi.write(0, buf, len)
    gpio.write(TFT_CS, 1) 
}

var tftTmpBuf = new Uint8Array(1024)

function tftPrepareWrite(x, y, x2, y2) {
    tftWrite8(0x2A, 0)
    tftTmpBuf[0] = x >> 8;
    tftTmpBuf[1] = x & 0xFF;
    tftTmpBuf[2] = x2 >> 8;
    tftTmpBuf[3] = x2 & 0xFF;
    tftWriteBuf(tftTmpBuf, 4, 1)
    tftWrite8(0x2B, 0)
    tftTmpBuf[0] = y >> 8;
    tftTmpBuf[1] = y & 0xFF;
    tftTmpBuf[2] = y2 >> 8;
    tftTmpBuf[3] = y2 & 0xFF;
    tftWriteBuf(tftTmpBuf, 4, 1)
    tftWrite8(0x2c, 0)
}

function tftFill(color) {
    tftPrepareWrite(0, 0, TFT_WIDTH-1, TFT_HEIGHT-1)
    for (var i = 0; i < TFT_WIDTH * 2; i++) {
        tftTmpBuf[i] = color;
    }
    for (var i = 0; i < TFT_HEIGHT; i++) {
        tftWriteBuf(tftTmpBuf, TFT_WIDTH * 2, 1)
    }
}

function tftInit(initCode) {
    for (var i = 0; i < initCode.length; i++) {
        var cmd = initCode[i]
        if (cmd[0] == -1) {
            os.sleepMs(cmd[1])
            continue
        }
        tftWrite8(cmd[0], 0)
        for (var j = 1; j < cmd.length; j++) {
            tftWrite8(cmd[j], 1)
        }
    }
}

tftInit([[1],[1],[-1,120],[17],[-1,120],[19],[54,8],[58,85],[-1,10],[178,12,12,0,51,51],[183,53],[187,40],[192,12],[194,1,255],[195,16],[196,32],[198,15],[208,164,161],[33],[42,0,0,0,229],[43,0,0,1,63],[41]])

